import { api_getSessionList } from '@/api/session'
import { api_getUserInfo } from '@/api/user'

export const sessionList = {
  props: {},
  data() {
    return {}
  },
  created() {
    // 如果vuex存在数据,则去除现有的list
    if (this.$store.state.sessionListData.list.length) {
      this.$store.commit('setSessionList', {
        list: [],
        isMore: false,
      })
    }

    this.getSessionList()

    // 监听收到的信息
    this.$bus.$on('chat', (item) => this.updateSession(item, 0, 'chat'))

    // 监听发送消息成功的通知
    this.$bus.$on('sendMsgSuccess', (item) => this.updateSession(item, 0, 'sendMsgSuccess'));

    // 监听通知
    this.$bus.$on('notice', (session) => this.updateSession(session, 2, 'notice'))
  },
  beforeDestroy() {
    this.$bus.$off('chat')
    this.$bus.$off('sendMsgSuccess')
    this.$bus.$off('notice')

    // this.cancelSessionListFunc('cancelSessionListFunc')
  },
  methods: {
    // 请求session数据
    getSessionList(lastTime) {
      api_getSessionList(lastTime, this).then(res => {
        if (res.data.code === 200) {
          let list = this.$store.state.sessionListData.list.slice()
          list.push(...res.data.list)
          this.$store.commit('setSessionListData', { list, isMore: list.length >= 20 })
          this.$store.commit('setTotalUnread', res.data.total)
        }
      })
    },

    // 更新session
    async updateSession(chat, type = 0, from) {
      console.log('update');
      // console.log(chat);
      // 浅拷贝, 避免直接修改vuex, 但是这里也可能会直接修改的里面的对象, 但是不是直接修改,关系不大
      let sessionList = this.$store.state.sessionListData.list.slice()
      let index = null;
      switch (type) {
        // 私聊
        case 0:
          index = sessionList.findIndex(item => item.sessionId === chat.sessionId)
          break;

          // 通知
        case 2:
          index = sessionList.findIndex(item => item.receiverId === -1)
          break;
      }

      // console.log(index);

      if (index !== -1) {
        let session = sessionList.splice(index, 1)[0]
        let currentSession = this.$store.state.currentSession
        // 如果不是当前session，未读数量 +1
        if (from !== 'sendMsgSuccess' && (!currentSession || session.sessionId != currentSession.sessionId || !(/^\/chat/.test(this.$route.path)))) {
          session.read++;
          // this.totalUnread++;
          this.$store.commit('setTotalUnread', ++this.$store.state.totalUnread)
        } else if (from !== 'sendMsgSuccess' && /^\/chat/.test(this.$route.path) && currentSession && session.sessionId == currentSession.sessionId) {
          // 如果是当前会话窗口，每接收一次信息就会执行一次这个位置
          // 为了避免频繁的调用http请求，这里使用socket告诉服务器当前所在的session
          window.$socket.emit('request', {
            function: 'resetUnread',
            params: {
              sessionId: session.sessionId,
              userId: this.$store.state.userInfo.id,
            }
          })
        }

        session.lastChat = chat.content;
        session.updatedAt = chat.updatedAt || chat.time
        // session.sessionId = chat.sessionId
        // console.log(session);
        sessionList.unshift(session)
      } else {
        // 请求用户信息
        let res = await api_getUserInfo({ userId: chat.talkerId })
        let sessionItem = this.createSessionItem(res.data.userInfo, chat.sessionId, chat.content)
        sessionList.unshift(sessionItem)
      }
      // 将最新sessionList保存到vuex中
      // 虽然每次都更新了整个数组,但是因为vue的虚拟dom机制,是不会导致所有dom重新渲染的
      this.$store.commit('setSessionListData', { list: sessionList, isMore: this.$store.state.sessionListData.isMore })
    },

    // 创建新的sessionItem
    createSessionItem(userInfo, sessionId, lastChat) {
      // console.log(userInfo);
      let sessionItem = {
        cover: userInfo.avatar,
        lastChat: lastChat,
        receiverId: userInfo.id,
        sessionId: sessionId,
        sessionName: userInfo.userName,
        type: 0,
        read: 0,
        updatedAt: new Date().getTime(),
        user: userInfo
      }
      // this.sessionList.unshift(sessionItem)
      return sessionItem
    },
  },
  computed: {},
}